
// 需要在vuex实例化前执行
// 在vue实例化前扩展全局变量
import { createStore } from 'vuex'
import deepmerge from 'deepmerge'
import Cookies from "js-cookie";
import { HttpUserInfo, HttpLangList } from "../service/base";
import layout from "./layout";
import dictionary from "./dictionary";
import jwt from 'jsonwebtoken';
import moment from "moment";

//初始化全局变量：语言，系统，组织
const setOrganization = function (state, payload = {}) {
    // console.log(payload,'payloadpayload')
    // payload = { id: payload.id, name: payload.name, userId: state.userinfo.id, logoUrl: payload.logoUrl || '', attach: payload.attach };
    payload = {
        ...payload,
        logoUrl: payload.logoUrl,
        userId: state.userinfo.id
    };
    global.SYSID = payload.id;
    state.organization = payload;
    // console.log('organization', JSON.stringify(payload));
    Cookies.set('organization', JSON.stringify(payload), { domain: global.DOMAIN, expires: 7 });
};

const langList = [{
    value: 'en',
    label: "English",
    icon: require('../image/en.png')
}, {
    value: 'zh-CN',
    label: "中文",
    icon: require('../image/zh-CN.png')
}];

global.LANG = Cookies.get("lang") || process.env.VUE_APP_LANG;
global.LANG = langList.some(item => item.value === global.LANG) ? global.LANG : "zh-CN";
global.orgRoleLabelMap = {
    SYSTEM: "system",
    CLIENT: "client",
    SERVICE: "service",
};
global.userRoleLabelMap = {
    CLMEM: "clmem",
    CLADM: "cladm",
    SPMEM: "spmem",
    SPADM: "spadm",
    SUPER: "super",
};
export default function storeInstance({ state = {}, getters = {}, mutations = {}, actions = {}, modules = {} } = {}, /*actionInit*/) {
    return createStore({
        state: {
            // isUpdateVersion: isUpdateVersion(),//版本号是否更新
            fullScreen: false,//是否全屏
            lang: global.LANG,
            langList,
            userinfo: JSON.parse(localStorage.USERINFO || '{}'),
            organization: JSON.parse(Cookies.get("organization") || '{}'),
            orgRoleLabelMap: global.orgRoleLabelMap,
            userRoleLabelMap: global.userRoleLabelMap,
            events: [],//全局通知事件
            ...state,
        },
        getters: {
            getOrgRoleLabelMap(state) {
                return state.orgRoleLabelMap;
            },
            getUserRoleLabelMap(state) {
                return state.userRoleLabelMap;
            },
            getContextOrganization(state) {
                return state.organization;
            },
            getAuthUser(state) {
                return state.userinfo;
            },
            getAuthUserOrgId(state) {
                return state.userinfo.orgId;
            },
            getSysId(state) {
                return state.organization.id;
            },
            isSuper(state) {
                return state.userinfo.isSuper == 1
            },
            getUserRoleLabel(state) {
                return state.userinfo.roleLabel;
            },
            getUserOrgRoleLabel(state) {
                return state.userinfo.organization.roleLabel;
            },
            getContextOrgRoleLabel(state) {
                return state.organization.roleLabel;
            },
            getFullScreen(state) {
                return state.fullScreen
            },
            ...getters,
        },
        mutations: {
            setOrganization,
            setUserInfo(state, payload = {}) {
                // console.log(payload,state,'statestatestate')
                const isSameUser = state.organization.id && payload.id == state.organization.userId;
                state.userinfo = payload;
                setOrganization(state, isSameUser ? state.organization : payload.organization);
                localStorage.setItem("USERINFO", JSON.stringify(payload), { scope: '', version: '' });
            },
            setLang(state, payload) {
                state.lang = global.LANG = state.langList.some(item => item.value === payload) ? payload : (process.env.VUE_APP_LANG || "zh-CN");
                Cookies.set('lang', state.lang, { domain: global.DOMAIN, expires: 7 });
                // axios.defaults.headers.common['Accept-Language'] = payload;
            },
            setFullScreen(state, payload = false) {
                state.fullScreen = payload;
            },
            storeEvent(state, payload = {}) {
                const { name, handler } = payload;
                if (name && typeof handler === 'function') {
                    state.events.push(payload)
                }
            },
            storeEmit(state, payload = {}) {
                const { name, data } = payload;
                if (name) {
                    state.events.forEach((e) => {
                        e.name === name && e.handler(data, state);
                    })
                }
            },
            storeClearEvent(state, payload) {
                if (!payload) return;
                if (payload === true) {
                    state.events = [];
                } else {
                    state.events = state.events.filter((e) => e.name !== name);
                }
            },
            ...mutations,
        },
        actions: {
            async actionGetUserInfo({ commit, dispatch, state },/*跳过验证passwordExpired*/isJump) {
                // eslint-disable-next-line no-console
                const token = Cookies.get("token");
                const clientTokenInfo = jwt.decode(token);

                // console.log('clientTokenInfo',clientTokenInfo);
                // console.log('clientTokenInfo.sub = uid ',parseInt(clientTokenInfo.sub,10) || 0);
                if (!token) throw new Error();
                global.AUTH_TOKEN = token;
                return HttpUserInfo().then(
                    res => {
                        let userinfo = state.userinfo,
                            isUpdate = false,
                            data = res.data;
                        // if (!isJump && data.passwordExpired === true) return Promise.reject({ passwordExpired: true })
                        isUpdate = (parseInt(clientTokenInfo.sub, 10) && parseInt(clientTokenInfo.sub, 10) != data.id);
                        isUpdate && sessionStorage.clear(true);
                        // console.log(parseInt(clientTokenInfo.sub,10),'---',data.id,'---',data,'---',isUpdate)
                        commit("setUserInfo", data);
                        return dispatch("actionInitBaseData", { updateInit: isUpdate });
                    }
                );
            },
            async actionGetLangList({ state }, payload = {}) {
                const lang = payload.lang || state.lang,
                    langKey = `LANG_${lang}_MAP`,
                    expiresKey = `LANG_${lang}_EXPIRES`,
                    expires = (payload.isForce ? null : localStorage[expiresKey]) || '2019-01-01 00:00:00',
                    callback = function (i18n, data = {}, isExpires = false) {
                        i18n.mergeLocaleMessage(lang, payload.isForce ? data : { ...JSON.parse(localStorage[langKey] || "{}"), ...data });
                        i18n.locale = lang;
                        localStorage.setItem(langKey, JSON.stringify(i18n['messages'][lang]), { scope: '', version: '', persistent: true });
                        if (isExpires) {
                            const date = new Date();
                            const zorePrefix = function (val) {
                                return val - 9 > 0 ? val : `0${val}`;
                            }
                            //提前几分钟的数据,保证响应时间出现间隔而漏掉
                            localStorage.setItem(expiresKey, `${date.getFullYear()}-${zorePrefix(date.getMonth() + 1)}-${zorePrefix(date.getDate())} ${zorePrefix(date.getHours())}:00:00`, { scope: '', version: '', persistent: true });
                        }
                    };
                return HttpLangList({ /*"systemId": process.env.VUE_APP_PROJECT_ID,*/contextId: 1, "search[EQ_locale]": lang, 'search[GT_opAt]': moment(expires).utc().format('YYYY-MM-DD HH:mm:ss') }).then(
                    res => {
                        const data = {};
                        res.data.forEach(item => {
                            data[item.langKey] = item.langValue;
                        });
                        return (i18n) => callback(i18n, data, true);
                    }
                ).catch(() => {
                    return Promise.resolve((i18n) => callback(i18n));
                });
            },
            async actionInitBaseData({ dispatch }, data = {}) {
                const updateInit = data.updateInit;
                const initData = async () => {
                    dispatch("dictionary/actionInit", updateInit);
                    // if (!actionInit) actionInit = Object.keys(modules).filter(key => {
                    //     return !!((modules[key] || {}).actions || {})['actionInit']
                    // }).map(key => {
                    //     return `${key}/actionInit`;
                    // })
                    // actionInit.forEach((key) => {
                    //     dispatch(key, updateInit);
                    // })
                    Object.keys(modules).filter(key => {
                        if (modules[key] && modules[key]['actions'] && modules[key]['actions']['actionInit']) {
                            dispatch(`${key}/actionInit`, updateInit);
                        }
                    })
                }
                initData().catch(() => {
                    // console.log(err)
                })
                return dispatch("layout/actionMenuList", updateInit);
            },
            ...actions,
        },
        modules: {
            ...modules,
            layout: layout(),
            dictionary: modules.dictionary ? deepmerge(dictionary, modules.dictionary) : dictionary,

        }
    })
}
